<?php

namespace App\Http\Controllers\Admin;

use App\Models\Photos;
use App\Models\PhotosCate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PhotosCateController extends Controller
{
    public function getCatCount(Request $request)
    {
        $model = PhotosCate::query();
        $model = $model->select('category_id', 'name');
        $result = $model->orderBy('sort', 'asc')->orderBy('category_id', 'desc')->get();
        $count = Photos::count();
        $datas = [
            [
                'category_id' => -1,
                'name' => '全部',
                'num' => $count
            ],
            [
                'category_id' => 0,
                'name' => '未分类',
                'num' => Photos::where('category_id', 0)->count(),
            ]
        ];
        foreach ($result as $val) {
            $datas[] = [
                'category_id' => $val->category_id,
                'name' => $val->name,
                'num' => Photos::where('category_id', $val['category_id'])->count(),
            ];
        }
        return showMsg('获取成功', 200, $datas);
    }


    public function index(Request $request)
    {
        $model = PhotosCate::query();
        $result = $model->orderBy('sort', 'asc')->orderBy('category_id', 'desc')->get();
        return showMsg('获取成功', 200, $result);
    }

    public function store(Request $request)
    {
        $data = $request->only(['name']);
        PhotosCate::create($data);
        return showMsg('添加成功', 200);
    }

    public function edit(Request $request)
    {
        $id = $request->get('category_id');
        $slide = PhotosCate::where('category_id', $id)->first();
        $data = $request->only(['name']);
        if ($slide) {
            PhotosCate::where('category_id', $id)->update($data);
        }
        return showMsg('更新成功', 200);
    }


    public function destroy(Request $request)
    {
        $ids = $request->get('category_id');
        if (empty($ids)) {
            return showMsg('请选择操作项', 201);
        }
        if (is_array($ids)) {
            foreach ($ids as $v) {
                PhotosCate::where('category_id', $v)->delete();
            }
        } else {
            PhotosCate::where('category_id', $ids)->delete();
        }
        return showMsg('删除成功', 200);
    }
}
